package com.costeaalex.MIDlets.remote.lists;

import javax.bluetooth.DataElement;
import javax.bluetooth.ServiceRecord;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import com.costeaalex.MIDlets.remote.BlueMIDlet;

public class ServiceList implements CommandListener
	{
	public List serviceList;
	private Command cmBack;
	private Command cmSelect;
	private BlueMIDlet midlet;
	private ServiceRecord[] servicesList;
	
	public ServiceList(ServiceRecord[] services, BlueMIDlet midl)
		{
		int i;
		int ind=0;
		DataElement servName;
		//DataElement servID;
		//DataElement servDes;
		String serviceName="";
		String connURL=null;
		
		midlet=midl;
		servicesList=services;
		
		serviceList = new List("Services Found", List.IMPLICIT);
		if(servicesList!=null)
			{
			for(i=0; i<services.length; i++)
				{
				servName = services[i].getAttributeValue(0x100);
				//servID = services[i].getAttributeValue(0x0004);
				//servDes = services[i].getAttributeValue(0x101)	;
				if(servName!=null)
					{
					try
						{
						connURL=services[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
						//serviceName = (String) servName.getValue()+"-"+(String) servDes.getValue()+"-"+((connURL==null)?"No URL":connURL)+"-"+services[i].getAttributeValue(0x001).getValue();
						serviceName = (String) servName.getValue();//+"-"+((connURL==null)?"No URL":connURL)+"-"+services[i].getAttributeValue(0x001).getValue();
						}
					catch (Exception e)
						{e.printStackTrace();}
					
					if(connURL!=null)
						{
						serviceList.insert(ind, serviceName, null);
						//serviceList.insert(ind, serviceName+"-"+(((Enumeration) servID.getValue()).nextElement()), null);
						ind++;
						}
					}
				}
			}
			
		cmBack=new Command("Back", Command.BACK, 1);
		cmSelect=new Command("Select", Command.SCREEN, 1);
		
		serviceList.addCommand(cmBack);
		serviceList.addCommand(cmSelect);
		serviceList.setCommandListener(this);
		}
	//midlet.serviceselected(selected);

	public void commandAction(Command c, Displayable d)
		{
		int sI;
		int i=0;
		int serviceIterator=0;
		String connURL=null;
		
		if(c==cmBack)
			{
			midlet.displayManager.returnToParent();
			}
				
		if(c==cmSelect)
			{
			sI=serviceList.getSelectedIndex();
			for(i=0; i<servicesList.length; i++)
				{
				connURL=servicesList[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
				if(connURL!=null)
					{
					if(sI==serviceIterator)
						break;
					else
						serviceIterator++;
					}
				}
			//if(servicesList[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false)!=null)	
				midlet.connect(servicesList[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false));
			}
		}
	}
